package com.kehutong.common.interceptor;
import org.coraframework.authz.exception.UnloginException;
import org.coraframework.bean.valid.ValidResult;
import org.coraframework.inject.Singleton;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.mvc.http.HttpReqMsg;
import org.coraframework.mvc.http.interceptor.Interceptor;
import org.coraframework.util.Objects;

import com.kehutong.common.errcode.Result;


/**
 * 系统拦截器
 * @author ThinkGem
 * @version 2013-6-6
 */
@Singleton
//@Exclude(WebService.class)
public class ValidInterceptor extends Interceptor {

	static final Logger logger = LoggerFactory.getLogger(ValidInterceptor.class);
	
	@Override
	public Object intercept(HttpReqMsg req) throws Exception {
		try {
			Object validResult = validField(req);
			if (Objects.nonNull(validResult)) {
				return validResult;
			}
			
			return req.invoke();
		} catch (UnloginException e) {
			throw e;
		}  catch (Throwable th) {
			throw new Exception(th);
		} 
	}

    private Object validField(HttpReqMsg req) {
    	if (!req.getDespatcher().valid()) {
    		return null;
    	}
    	
    	ValidResult rs = req.getValidResult();
    	if (rs.hasError()) {
    		return Result.error(0, rs.getErrorMessage());
    	}
    	
    	return null;
    }

}
